from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from apps.goods.models import SKUImage, SKU
from apps.meiduo_mall_admin.serializers.image import ImageSeriazlier, SKUSeriazlier
from apps.meiduo_mall_admin.utils import PageNum


class ImageView(ModelViewSet):
    """获取图片列表逻辑"""

    # 图片序列化器
    serializer_class = ImageSeriazlier
    # 图片查询集
    queryset = SKUImage.objects.all()
    # 分页
    pagination_class = PageNum

    # 重写create方法保存图片
    def create(self, request, *args, **kwargs):
        # 导入fsatdfs包
        from fdfs_client.client import Fdfs_client
        # 创建链接对象
        client = Fdfs_client("meiduo_mall/utils/fastdfs/client.conf")
        # 获取前端传递的图片数据
        data = request.FILES.get("image")
        # 上传图片到fastDFS
        serializer = client.upload_appender_by_buffer(data.read())
        # 判断是否上传成功
        if serializer["Status"] != "Upload successed.":
            return Response(status=403)
        # 获取上传后的路径
        image_url = serializer['Remote file_id']
        # 获取sku_id
        sku_id = request.data.get("sku")
        # 保存图片
        img = SKUImage.objects.create(sku_id=sku_id, image=image_url)
        # 返回结果
        return Response({
            "id":img.id,
            "sku":sku_id,
            "image":img.image.url
        },status=201)

    # 重写update方法用于更新图片数据
    def update(self, request, *args, **kwargs):
        # 导入fsatdfs包
        from fdfs_client.client import Fdfs_client
        # 创建链接对象
        client = Fdfs_client("meiduo_mall/utils/fastdfs/client.conf")
        # 获取前端传递的图片数据
        data = request.FILES.get("image")
        # 上传图片到fastDFS
        serializer = client.upload_appender_by_buffer(data.read())
        # 判断是否上传成功
        if serializer["Status"] != "Upload successed.":
            return Response(status=403)
        # 获取上传后的路径
        image_url = serializer["Remote file_id"]
        # 获取sku_id
        sku_id = request.data.get("sku")
        # 查询图片对象
        sku_image = SKUImage.objects.get(id=kwargs["pk"])
        # 更新图片
        sku_image.image = image_url
        # 保存更新后的图片
        sku_image.save()
        # 返回结果
        return Response({
            "id":sku_image.id,
            "sku":sku_id,
            "image":sku_image.image.url
        },status=201)


class SKUView(APIView):
    """获取sku表id"""
    def get(self,request):
        # 获取sku所有数据
        data = SKU.objects.all()
        # 序列化器
        serializer = SKUSeriazlier(data,many=True)
        # 返回响应
        return Response(serializer.data)